﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Truextend.CoffeShop.Model;
using Truextend.Common.Data;
using Truextend.CoffeShop.Bussiness.Interfaces;

namespace Truextend.CoffeShop.Bussiness
{
    public class ConsumptionManager : Repository<Consumption> , IConsumptionManager
    {
        IDetailManager detailManager = null;

        public ConsumptionManager(IUnitOfWork unitOfWork, IDetailManager detailManager) : base(unitOfWork) {
            this.detailManager = detailManager;
        }

        public void AddConsumptionByInternalProducts(Consumption consumption)
        {
            this.Add(consumption);
        }

        public void AddConsumptionByInternalProducts(int productId, Consumption consumption)
        {
            
            detailManager.AddDetailForProductID(new Detail(), productId);

            Detail detail = detailManager.GetLastDetail();
            consumption.DetailReference.EntityKey = detail.EntityKey;

            this.Add(consumption);
        }

        public void AddConsumptionByOrder(int detailId, Consumption consumption)
        {
            Detail detail = detailManager.GetDetailById(detailId);

            consumption.DetailReference.EntityKey = detail.EntityKey;

            this.Add(consumption);

        }

        public IList<Consumption> GetAllConsumptionsOfADetail(int detailId){

            var context = (CoffeShopEntities)Context;

            var info = from p in context.Consumption where p.Detail.DetailId == detailId select p;

            return info.ToList();
        }



        public Consumption GetConsumptionForDetailAndUserID(int detailId, int userId)
        {
            var context = (CoffeShopEntities)Context;

            var info = from p in context.Consumption where p.Detail.DetailId == detailId && p.UserId == userId select p;

            return info.FirstOrDefault();
        }


        public void DeleteConsumption(Consumption consumption)
        {
            var context = (CoffeShopEntities) Context;

            var consumptionDelete =
                (from p in context.Consumption where p.ConsumptionId == consumption.ConsumptionId select p).First();

            this.Delete(consumptionDelete);
            this.Save();
        }
    }
}
